package me.ezitku.base.service

import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import me.ezitku.base.IServiceProcss
import me.ezitku.base.extensions.startService

class RemoteService : Service() {
    private var binder: MyBinder? = null
    lateinit private var conn: ServiceConnection
    lateinit var startClass: Class<*>
    override fun onBind(intent: Intent?): IBinder? {
        return binder
    }

    override fun onCreate() {
        super.onCreate()
        startClass = LocalService::class.java
        if (binder == null) {
            binder = MyBinder()
        }
        conn = serviceConn {
            disConnected {
                bindService(Intent(this@RemoteService, startClass), conn, Context.BIND_IMPORTANT)
                startService(startClass)
            }
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        bindService(Intent(this, startClass), conn, Context.BIND_IMPORTANT)
//        startForeground(startId, createNotification("Title", "Content"))
        return START_STICKY
    }


    class MyBinder : IServiceProcss.Stub() {
        override fun getProccessName(): String {
            return ""
        }

        fun getService(): RemoteService {
            return RemoteService()
        }

    }

//    inner class MyServiceConnection : ServiceConnection {
//        override fun onServiceDisconnected(name: ComponentName?) {
//            bindService(Intent(this@RemoteService, startClass), conn, Context.BIND_IMPORTANT)
//            startService(startClass)
//        }
//
//        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
//            var sss = (service as RemoteService.MyBinder).getService()
//
//        }
//
//    }


    override fun onDestroy() {
        super.onDestroy()
//        startForeground(0, createNotification("Title", "Content"))
    }

}


fun serviceConn(action: serviceConnection.() -> Unit): ServiceConnection {
    return serviceConnection().apply(action)
}

class serviceConnection : ServiceConnection {

    var _connected: ((name: ComponentName, service: IBinder) -> Unit)? = null
    var _disConnected: ((name: ComponentName) -> Unit)? = null

    override fun onServiceDisconnected(name: ComponentName) {
        _disConnected?.invoke(name)
    }

    override fun onServiceConnected(name: ComponentName, service: IBinder) {
        _connected?.invoke(name, service)
    }

    fun connected(connected: (name: ComponentName, service: IBinder) -> Unit) {
        _connected = connected
    }

    fun disConnected(disConnected: (name: ComponentName) -> Unit) {
        _disConnected = disConnected
    }

}